import re

from django_redis import get_redis_connection
from rest_framework import serializers

from users.models import User
from .utils import check_sms_code


class RegisterSmscodeSerializer(serializers.Serializer):

    text = serializers.CharField(label='图片验证码', max_length=4, min_length=4, required=True)
    image_code_id = serializers.UUIDField(label='uuid')

    # 多个字段校验
    def validate(self, attrs):

        # 获取用户数据
        text = attrs.get('text')
        # 获取redis数据
        # 先连接redis数据库
        redis_conn = get_redis_connection('code')
        # 获取数据
        image_code_id = attrs.get('image_code_id')
        redis_text = redis_conn.get('img_%s' % image_code_id)
        # 判断是否过期
        if redis_text is None:
            raise serializers.ValidationError('图片验证码已过期')
        # 比对
        if redis_text.decode().lower() != text.lower():
            raise serializers.ValidationError('输入不一致')

        return attrs


class SmscodeSerializer(serializers.Serializer):

    sms_code = serializers.CharField(label='短信验证码')

    # 短信验证码
    def validate(self, attrs):
        mobile = self.context['mobile']
        if not re.match(r'1[3-9]\d{9}',mobile):
            raise serializers.ValidationError('手机号格式错误')
        # 短信验证码
        # 获取用户输入的数据
        sms_code = attrs['sms_code']

        sRet = check_sms_code(sms_code, mobile)
        if sRet == 'TimeOut':
            raise serializers.ValidationError('短信验证码已过期')

        elif sRet == 'ValueError':
            raise serializers.ValidationError('短信验证码输入有误')

        return attrs

class PasswordSerializer(serializers.ModelSerializer):
    password2 = serializers.CharField(label='校验密码', allow_null=False, allow_blank=False, write_only=True)

    class Meta:
        model = User
        fields = ('password','password2', )

    def validate(self, attrs):
        # 验证密码和确认密码
        # 获取数据
        password = attrs.get('password')
        password2 = attrs.get('password2')
        # 比对
        if password != password2:
            raise serializers.ValidationError('两次输入密码不一致')
        del attrs['password2']
        return attrs



    def update(self, instance, validated_data):
        password = validated_data.get('password')
        instance.set_password(password)
        instance.save()
        return instance